package com.yj.auto.core.web.system.service;

import java.util.List;

import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.yj.auto.Constants;
import com.yj.auto.core.base.annotation.Service;
import com.yj.auto.core.base.model.QueryModel;
import com.yj.auto.core.jfinal.base.BaseCache;
import com.yj.auto.core.jfinal.base.BaseService;
import com.yj.auto.core.web.system.model.Role;
import com.yj.auto.core.web.system.model.RoleResource;

/**
 * Role 管理 描述：
 */
@Service(name = "roleSrv")
public class RoleService extends BaseService<Role> implements BaseCache {

	private static final Log logger = Log.getLog(RoleService.class);

	public static final String SQL_LIST = "system.role.list";

	public static final Role dao = new Role().dao();
	public static final RoleResource resDao = new RoleResource().dao();

	@Override
	public Role getDao() {
		return dao;
	}

	@Override
	public SqlPara getListSqlPara(QueryModel query) {
		if (StrKit.isBlank(query.getOrderby())) {
			query.setOrderby("sort");
		}
		return getSqlPara(SQL_LIST, query);
	}

	// 根据角色代码查询
	public Role getByCode(String code) {
		String sql = "select * from t_sys_role where code=?";
		return dao.findFirst(sql, code);
	}

	public boolean save(Role model) {
		boolean success = model.save();
		if (success) {
			saveResource(model.getId(), model.getResources());
		}
		return success;
	}

	public boolean update(Role model) {
		boolean success = model.update();
		if (success) {
			deleteResource(model.getId());
			saveResource(model.getId(), model.getResources());
		}
		return success;
	}


	public boolean delete(Integer... ids) {
		deleteResource(ids);
		return super.delete(ids);
	}

	public List<RoleResource> getResources(Integer id) {
		String sql = "select * from t_sys_role_resource where role_id=?";
		List<RoleResource> list = resDao.find(sql, id);
		return list;
	}

	private void saveResource(Integer id, List<RoleResource> resources) {
		if (null == resources)
			return;
		for (RoleResource r : resources) {
			r.setRoleId(id);
			r.save();
		}
	}

	private void deleteResource(Integer... id) {
		resDao.deleteByColumn("role_id", id);
	}

	@Override
	public void loadCache() {
		QueryModel query = new QueryModel();
		query.setOrderby("sort");
		query.setState(Constants.DATA_STATE_VALID);
		List<Role> list = find(SQL_LIST, query);
		for (Role r : list) {
			r.setResources(getResources(r.getId()));
			addCache(r.getId(), r);
		}
	}

	@Override
	public String getCacheName() {
		return Constants.CACHE_NAME_ROLE;
	}
}